package com.imay.live.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.imay.base.activity.BaseActivity;
import com.imay.base.util.StringUtil;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.dialog.Dialoger;
import com.imay.live.Constants;
import com.imay.live.R;
import com.imay.live.activity.ChatActivity;
import com.imay.live.activity.FollowListActivity;
import com.imay.live.activity.HoldCallLiveActivity;
import com.imay.live.activity.MainActivity2;
import com.imay.live.activity.MarketActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.ProfileRankingActivity;
import com.imay.live.activity.RoomLiveNormalActivity;
import com.imay.live.activity.RoomLiveShortActivity;
import com.imay.live.activity.RoomPushShortActivity;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.activity.discovery.DynamicActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.activity.dynamics.LabelFeedsActivity;
import com.imay.live.activity.family.FamilyActivity;
import com.imay.live.activity.family.FamilyHomeActivity;
import com.imay.live.activity.family.helper.NimLogin;
import com.imay.live.activity.profit.IncomeActivity;
import com.imay.live.activity.recharge.RechargeActivity;
import com.imay.live.adapter.DynamicsGridAdapter;
import com.imay.live.adapter.ProfileRecommendAdapter;
import com.imay.live.adapter.SupperTypeAdapter;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.dynamics.OnTouchHeartListener;
import com.imay.live.heartlikeslib.hearthikesview.HeartLikeView;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.LevelHelper;
import com.imay.live.helper.MediaHelper;
import com.imay.live.helper.NumberHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.DataSetListener;
import com.imay.live.manager.DataSetManager;
import com.imay.live.manager.DynamicsLinearManager2;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.manager.UnreadManager;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.model.CreateFollowModel;
import com.imay.live.model.FamilyUserInfo;
import com.imay.live.model.FeedModel;
import com.imay.live.model.ProfileLikeDynamicModel;
import com.imay.live.model.ProfileSocketMoneyModel;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.model.SysparamModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.ResultNoData;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.user.UserUpdataLvNotify;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.view.refresh.RefreshView;
import com.imay.live.viewtype.SupperModelType;
import com.imay.tbas_api.IMYTBASObject;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.yalantis.ucrop.UCrop;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.imay.dialog.Dialoger.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.dialog.Dialoger.SYS_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.live.activity.ProfileActivity.FROM_TYPE_SHORT_LIVE;
import static com.imay.live.manager.UnreadManager.TYPE_UNREAD_CALL_LIVE_PROFILE;
import static com.imay.live.params.IMParams.CONFIG_SWITCH_RECHARGE_TIP;
import static com.imay.live.params.IMParams.CONFIG_VALUE_RECHARGE_TIP_URL1;
import static com.imay.live.params.IMParams.CONFIG_VALUE_RECHARGE_TIP_URL2;
import static com.imay.live.proto.ResultCode.CodeSuccess;


public class ProfileFragment extends BaseRequestFragment implements View.OnClickListener, OnTouchHeartListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, DataSetListener {

    private static String ARG_PARAM1 = "param1";
    private static String ARG_PARAM2 = "param2";
    private RecyclerView rv_recommend, rcv_profile_dynamic;
    private RelativeLayout mUserInfoHeaderView;
    private long userId;
    private TextView tv_user_name, tv_imay_number, tv_sign, tv_website, tv_fans_count, tv_follow_count, tv_balance, tv_meili, tv_marcket, tv_anchor_level, tv_user_level, tv_profile_user_family_nick;
    private ImageView iv_user_head_img;
    private Button btn_follow;
    private ImageView iv_recommend;
    private View line_other_profile;
    private RadioButton rb_mine_tab_mine, rb_mine_tab_short_live, rb_mine_tab_follow;
    private LinearLayout ll_recommend;
    private String loadUserCommand, loadMineDynamicCommand, loadMineSupperCommand, loadMineDynamicLikeCommand, createFollowCommand, cancelFollowCommand, loadRecommendUserCommand, loadFamilyUserCommand;
    private int mineDynamicMaxId;
    private long mineSupperMaxId;
    private int beforeTime;
    private int count = 20;
    private int suppercount = 21;
    private List<Object> mineDynamicList, likeDynamicList;
    private DynamicsGridAdapter mineAdapter;
    private SupperTypeAdapter supperTypeAdapter;

    private DynamicsLinearManager2 linearManager;
    private HeartLikeView hlv_profile_dynamics_like;
    private UserInfoModel userInfoModel;
    private IMYTBASObject userInfoChangeListener;
    private IMYTBASObject shortLiveChangeListener;

    private int currentTab;
    public static final int MINE = 0;
    public static final int FOLLOW = 1;
    public static final int SUPPER = 2;//超胆播
    private ImageView iv_profile_vip;
    private ProfileRecommendAdapter profileRecommendAdapter;
    private TwinklingRefreshLayout profile_dynamics_trl_refresh;
    private String likeCreateRequest;
    private String likeDelRequest;
    private List<UserModel> recommendUserModels;
    private FollowControl followControl;
    private IMYTBASObject followChangeListener;
    private IMYTBASObject moneyInfoListener;
    private IMYTBASObject levelListener;
    private String updateInfoCommand;

    private int playerPosition;
    private IMYTBASObject dynamicsupdate;
    private List<Object> tempList;
    private ArrayList<MultiItemEntity> mdatas;
    private RelativeLayout ll_profile_live_statu;
    private View view_supper_layout;

    private HorizontalDividerItemDecoration itemDecoration;
    private HorizontalDividerItemDecoration itemSupperDecoration;
    private View ll_empty_view;
    private View fl_empty_view_profile;
    private TextView tv_live_profile;
    private ImageView iv_live_statu_profile;
    private View tv_unread_call_live_profile;

    private boolean isInstance = true;
    private DataSetManager mDataSetManager;
    private boolean isCallLiveClicked;
    //区分第一次加载和下拉刷新
    private int fromType;

    private FamilyUserInfo familyUserInfo;

    public static ProfileFragment newInstance(long userId) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_PARAM1, userId);
        fragment.setArguments(args);
        return fragment;
    }

    public static ProfileFragment newInstance(long userId, int fromType) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_PARAM1, userId);
        args.putInt(ARG_PARAM2, fromType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_profile;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.profile_dynamics_trl_refresh));
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            userId = getArguments().getLong(ARG_PARAM1, 0);
            fromType = getArguments().getInt(ARG_PARAM2, 0);
        }
        mineDynamicList = new ArrayList<>();
        likeDynamicList = new ArrayList<>();
        tempList = new ArrayList<>();
        mdatas = new ArrayList<MultiItemEntity>();
        supperTypeAdapter = new SupperTypeAdapter(mdatas);
        mineAdapter = new DynamicsGridAdapter();
        supperTypeAdapter.setOnItemChildClickListener(this);
        mineAdapter.setOnItemChildClickListener(this);


        bindViews();

        if (itemDecoration == null) {
            itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                    .colorResId(R.color.bg_f8)
                    .sizeResId(R.dimen.size_4dp)
                    .build();
        }


        rcv_profile_dynamic.setHasFixedSize(true);
        rcv_profile_dynamic.addItemDecoration(itemDecoration);

        linearManager = new DynamicsLinearManager2(getFragmentManager(), getActivity(), rcv_profile_dynamic, getContentView(), this, true, DynamicsLinearManager2.TYPE_PROFILE);


        setViewHide();
        addListener();
        loadData();
        if (isHomeProfile()) {
            initUserInfoChangeListener();
            addLevelReceiveListener();
            addMoneyInfoReceiveListener();
            initShortLiveChangeListener();
        } else {
            recommendUserModels = new ArrayList<>();
            followControl = new FollowControl();
        }
        registerSocketNotify();
        if (userId != 0) {/*非主页个人页*/
            profile_dynamics_trl_refresh.setPadding(0, 0, 0, 0);
        }

        mDataSetManager = DataSetManager.Builder.create(this).build();
        registerDynamicsUpdate();

        if (fromType == FROM_TYPE_SHORT_LIVE) {
            currentTab = SUPPER;
            rb_mine_tab_short_live.setChecked(true);
        }
        swicthLayout();

        MobclickAgent.onEvent(getActivity(), "personal_open");
    }

    private void registerDynamicsUpdate() {
        // 监听数据改变进行布局刷新 1、评论；2、点赞；3、发表动态
        dynamicsupdate = new IMYTBASObject(false);
        dynamicsupdate.stringCommand = EventHelper.EVENT_DYNAMICS_UPDATE;
        dynamicsupdate.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (!TextUtils.isEmpty(imytbasObject.stringData)) {
                    JSONObject jsonObject = JSON.parseObject(imytbasObject.stringData);
                    int action = jsonObject.getIntValue(Constants.DynamicsUpdate.DYNAMICS_ACTION_KEY);
                    FeedModel feed = JSON.parseObject(imytbasObject.stringData, FeedModel.class);
                    List<Object> objects = linearManager.getmAdapter().getData();
                    switch (action) {
                        case Constants.DynamicsUpdate.ACTION_DYNAMICS_MODIFY:
                            /**
                             * 线性布局
                             */
                            int position = 0;
                            for (Object object : objects) {
                                if (object instanceof FeedModel) {
                                    FeedModel item = (FeedModel) object;
                                    if (item.getFeedId() == feed.getFeedId()) {
                                        item.setMsg(feed.getMsg());
                                        item.setCountLike(feed.getCountLike());
                                        item.setIsLike(feed.isIsLike());
                                        item.setCountComment(feed.getCountComment());
                                        item.setAtUsers(feed.getAtUsers());
                                        item.setLabels(feed.getLabels());
                                        break;
                                    }
                                }
                                position++;
                            }
                            linearManager.getmAdapter().notifyItemChanged(position + linearManager.getmAdapter().getHeaderLayoutCount());


                            break;
                        case Constants.DynamicsUpdate.ACTION_DYNAMICS_DEL:
                            /**
                             * 整理我的动态数据
                             */
                            for (Object object : mineDynamicList) {
                                if (object instanceof FeedModel) {
                                    FeedModel item = (FeedModel) object;
                                    if (item.getFeedId() == feed.getFeedId()) {
                                        mineDynamicList.remove(object);
                                        break;
                                    }
                                }
                            }
//                            ThreadManager.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    bindShortLiveAdapter();
//                                }
//                            });
                    }
                }
            }
        });
        dynamicsupdate.addEventListenWithTBASObject();
    }

    private void bindViews() {

        mUserInfoHeaderView = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(R.layout.view_profile_header, null);
        rcv_profile_dynamic = $(R.id.rcv_profile_dynamic);
        tv_user_name = $(R.id.tv_profile_user_name, mUserInfoHeaderView);
        tv_imay_number = $(R.id.tv_proflie_imay_number, mUserInfoHeaderView);
        tv_sign = $(R.id.tv_profile_sign, mUserInfoHeaderView);
        tv_website = $(R.id.tv_profile_website, mUserInfoHeaderView);
        tv_follow_count = $(R.id.tv_profile_follow_count, mUserInfoHeaderView);
        tv_balance = $(R.id.tv_profile_balance, mUserInfoHeaderView);
        tv_meili = $(R.id.tv_profile_meili, mUserInfoHeaderView);
        iv_user_head_img = $(R.id.iv_profile_head_img, mUserInfoHeaderView);
        btn_follow = $(R.id.btn_profile_follow, mUserInfoHeaderView);
        iv_recommend = $(R.id.iv_profile_recommend, mUserInfoHeaderView);
        line_other_profile = $(R.id.line_other_profile, mUserInfoHeaderView);
        rb_mine_tab_short_live = $(R.id.rb_profile_tab_short_live, mUserInfoHeaderView);
        rb_mine_tab_mine = $(R.id.rb_profile_tab_mine, mUserInfoHeaderView);
        rb_mine_tab_follow = $(R.id.rb_profile_tab_follow, mUserInfoHeaderView);
        tv_marcket = $(R.id.tv_profile_marcket, mUserInfoHeaderView);
        ll_recommend = $(R.id.ll_profile_recommend, mUserInfoHeaderView);
        rv_recommend = $(R.id.profile_recommend, mUserInfoHeaderView);
        tv_anchor_level = $(R.id.tv_profile_anchor_level, mUserInfoHeaderView);
        tv_user_level = $(R.id.tv_profile_user_level, mUserInfoHeaderView);
        tv_fans_count = $(R.id.tv_profile_fans_count, mUserInfoHeaderView);
        ll_profile_live_statu = $(R.id.ll_profile_live_statu, mUserInfoHeaderView);
        iv_profile_vip = $(R.id.iv_profile_vip, mUserInfoHeaderView);
        hlv_profile_dynamics_like = $(R.id.hlv_profile_dynamics_like);
        profile_dynamics_trl_refresh = $(R.id.profile_dynamics_trl_refresh);
        view_supper_layout = $(R.id.view_supper_layout, mUserInfoHeaderView);
        ll_empty_view = $(R.id.ll_empty_view, mUserInfoHeaderView);
        fl_empty_view_profile = $(R.id.fl_empty_view_profile, mUserInfoHeaderView);
        tv_live_profile = $(R.id.tv_live_profile, mUserInfoHeaderView);
        iv_live_statu_profile = $(R.id.iv_live_statu_profile, mUserInfoHeaderView);
        tv_unread_call_live_profile = $(R.id.tv_unread_call_live_profile, mUserInfoHeaderView);
        tv_profile_user_family_nick = $(R.id.tv_profile_user_family_nick, mUserInfoHeaderView);
        $(R.id.ll_profile_right, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_profile_right_family, mUserInfoHeaderView).setOnClickListener(this);


        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        /*DividerItemDecoration itemDecoration = new DividerItemDecoration(getActivity(),
                LinearLayoutManager.VERTICAL);*/
//
        //rv_recommend.addItemDecoration(itemDecoration);
        rv_recommend.setLayoutManager(layoutManager);
        RefreshView headerView = new RefreshView(getActivity());
        profile_dynamics_trl_refresh.setHeaderView(headerView);
        profile_dynamics_trl_refresh.setBottomView(new LoadingView(getActivity()));
        profile_dynamics_trl_refresh.setEnableLoadmore(true);
        profile_dynamics_trl_refresh.setEnableOverScroll(false);

        if (isHomeProfile()) {
            Drawable drawable = getActivity().getResources().getDrawable(R.drawable.profile_dynamics_mine_grid_selecter);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
            rb_mine_tab_mine.setCompoundDrawables(null, drawable, null, null);

        }


//
    }

    private void addListener() {
        $(R.id.ll_profile_ranking_list, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_fans, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_follow, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_balance, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_profile_meili, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.ll_balance, mUserInfoHeaderView).setOnClickListener(this);
        $(R.id.iv_profile_recommend, mUserInfoHeaderView).setOnClickListener(this);
        iv_user_head_img.setOnClickListener(this);
        btn_follow.setOnClickListener(this);
        tv_website.setOnClickListener(this);
        ll_profile_live_statu.setOnClickListener(this);
        profile_dynamics_trl_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                refreshData();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadMore();
            }
        });


        rb_mine_tab_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentTab == FOLLOW) {
                    return;
                }
                MobclickAgent.onEvent(getActivity(), "personal_my_attention");
                currentTab = FOLLOW;
                swicthLayout();
                bindFollowAdapter(likeDynamicList);

            }
        });
        rb_mine_tab_mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentTab == MINE) {
                    return;
                }
                currentTab = MINE;
                swicthLayout();
                bindMineAdapter(mineDynamicList);
            }
        });
        rb_mine_tab_short_live.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentTab == SUPPER) {
                    return;
                }
                currentTab = SUPPER;
                swicthLayout();
                bindShortLiveAdapter();

            }
        });
    }


    private void refreshView() {
        if (userInfoModel.getUser() == null) {
            return;
        }
        tv_user_name.setText(userInfoModel.getUser().getNick());
        tv_imay_number.setText(String.format(getString(R.string.mine_room_id), userInfoModel.getUser().getRoomId()));
        tv_sign.setText(userInfoModel.getIntro());
        tv_fans_count.setText(NumberHelper.getFormatNumberFollow(userInfoModel.getStat().getFollower()));
        tv_follow_count.setText(NumberHelper.getFormatNumberFollow(userInfoModel.getStat().getFollow()));
        refreshMoneyView();
        tv_anchor_level.setText(userInfoModel.getUser().getLiveLevel() + "");
        tv_user_level.setText(userInfoModel.getUser().getUserLevel() + "");
        tv_user_level.setBackgroundResource(LevelHelper.getUserLevelResId(userInfoModel.getUser().getUserLevel()));
        tv_anchor_level.setBackgroundResource(LevelHelper.getLiveLevelResId(userInfoModel.getUser().getLiveLevel()));
        GlideUtil.loadCircleImage(iv_user_head_img, userInfoModel.getUser().getImgHead(), R.mipmap.pnl_00_head108);
        Drawable drawable;
        if (1 == userInfoModel.getUser().getSex()) {
            drawable = getResources().getDrawable(R.mipmap.ico_00boy);
        } else {
            drawable = getResources().getDrawable(R.mipmap.ico_00girl);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_user_name.setCompoundDrawables(drawable, null, null, null);
        btn_follow.setText(userInfoModel.getUser().isMyFollow() ? R.string.has_followed : R.string.create_follow);
        iv_profile_vip.setBackgroundResource(LevelHelper.getVIPIcon(userInfoModel.getUser().getVip()));
        tv_website.setText(userInfoModel.getWebsite());
        if (isHomeProfile()) {
            setCallLiveRedVisible(userInfoModel.getCallLiveCount() > 0);
            if (getActivity() instanceof MainActivity2) {
                ((MainActivity2) getActivity()).showCallLiveBubble(userInfoModel.getCallLiveCount());
            }
        }
        refreshLiveStatu();
        if (TextUtils.isEmpty(userInfoModel.getUser().getDesignation())) {
            tv_profile_user_family_nick.setVisibility(View.GONE);
        } else {
            tv_profile_user_family_nick.setVisibility(View.VISIBLE);
            tv_profile_user_family_nick.setText(userInfoModel.getUser().getDesignation());
        }
    }

    private void refreshMoneyView() {
        tv_balance.setText(NumberHelper.getFormatNumberMoney(userInfoModel.getMoney().getDiamond()));
        tv_meili.setText(String.format(getString(R.string.mine_meili), NumberHelper.getFormatNumberMoney(userInfoModel.getMoney().getMeili())));
    }


    @Override
    public void onClick(View v) {
        if (userInfoModel == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.ll_profile_ranking_list:
                ProfileRankingActivity.start(getActivity(), userId);
                MobclickAgent.onEvent(getActivity(), "personal_click_lists");
                break;
            case R.id.ll_fans:
                FollowListActivity.start(getActivity(), FollowListActivity.TYPE_FANS, userId);
                MobclickAgent.onEvent(getActivity(), "personal_click_follower");
//                FansListActivity.start(getActivity());
                break;
            case R.id.ll_follow:
                FollowListActivity.start(getActivity(), FollowListActivity.TYPE_FOLLOW, userId);
                MobclickAgent.onEvent(getActivity(), "personal_click_attention");
                break;
            case R.id.ll_profile_meili:
                saveUserInfo(userInfoModel);
                IncomeActivity.start(getActivity());
                MobclickAgent.onEvent(getActivity(), "personal_click_income");
                break;
            case R.id.ll_balance:
                saveUserInfo(userInfoModel);
                RechargeActivity.start(getActivity());
                MobclickAgent.onEvent(getActivity(), "personal_click_balance");
                break;
//            case R.id.tv_mine_recharge:
//                RechargeActivity.start(getActivity());
//                break;
            case R.id.ll_profile_right:

                if (isHomeProfile()) {
//                    ((MainActivity2) getActivity()).showMarketPannel(null);
                    MarketActivity.start(getActivity(), 0);
                    MobclickAgent.onEvent(getActivity(), "personal_click_mall");

                } else {
                    if (isSelf()) {
                        ToastUtil.show(getActivity(), R.string.chat_self);
                        return;
                    }
                    if (userInfoModel.getUser() != null) {
                        ChatActivity.start(getActivity(), userId, userInfoModel.getUser().getNick());
                    }
                }
                break;
            case R.id.ll_profile_right_family:
                if (!AccountManager.getInstance().isLogined()) {
                    ToastUtil.show(getActivity(), R.string.str_login_lose);
                    return;
                }
                if (isHomeProfile()) {
                    if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
                        // 登录网易
                        if (!NimLogin.getInstance().isLoginNim()) {
                            FamilyAccountManager.getInstance().loginNim();
                        }
                        FamilyHomeActivity.startActivity(getActivity(), FamilyHomeActivity.ME);
                    } else {
                        FamilyActivity.startActivity(getActivity());
                    }
                } else {
                    if (familyUserInfo != null && familyUserInfo.getFamily() != null) {
                        if (familyUserInfo.getFamilyUser().getFamilyId() != 0) {
                            FamilyHomeActivity.startActivity(getActivity(), FamilyHomeActivity.OTHERS, familyUserInfo.getFamily());
                        } else {
                            ToastUtil.show(getActivity(), R.string.str_family_no_note);
                        }
                    }
                }
                break;
            case R.id.iv_profile_recommend:
                if (recommendUserModels == null || recommendUserModels.isEmpty()) {
                    getSuggest();
                }
                if (ll_recommend.getVisibility() == View.GONE) {
                    ll_recommend.setVisibility(View.VISIBLE);
                    iv_recommend.setImageResource(R.mipmap.btn_05_more_on);
                } else {
                    ll_recommend.setVisibility(View.GONE);
                    iv_recommend.setImageResource(R.mipmap.btn_05_more_d);
                }
                if (currentTab == FOLLOW || currentTab == MINE) {
                    linearManager.getmAdapter().notifyItemChanged(1);
                }
                break;
            case R.id.btn_profile_follow:
                if (isSelf()) {
                    ToastUtil.show(getActivity(), R.string.follow_self);
                    return;
                }
                if (userInfoModel.getUser() != null) {
                    followControl.followChanged(getActivity().getApplicationContext(), userInfoModel.getUser(), false);
                }
                break;
            case R.id.tv_profile_website:
                WebViewActivity.startActivity(getActivity(), userInfoModel.getWebsite());
                break;
            case R.id.iv_profile_head_img:
                if (isHomeProfile()) {
                    MediaHelper.showMediaSheet(getActivity());
                }

                break;
            case R.id.ll_profile_live_statu:

                if (userInfoModel.getUser().getLiveStatus() == 1) {
                    getRoomInfo(userInfoModel.getUser().getRoomId());
                    MobclickAgent.onEvent(getActivity(), "zhibo_click");
                } else {
                    if (isHomeProfile() || isSelf()) {
                        HoldCallLiveActivity.startActivity(getActivity(), userInfoModel.getUser().getUid(), userInfoModel.getUser().getNick());
                        setCallLiveRedVisible(false);
                        UnreadManager.getInstance().postUnreadEvent(TYPE_UNREAD_CALL_LIVE_PROFILE, 0);
                        MobclickAgent.onEvent(getActivity(), "zizhaohuan_click");
                    } else {
                        if (userInfoModel.getUser().isMyFollow()) {
                            isCallLiveClicked = true;
                            loaUserInfo();
                            MobclickAgent.onEvent(getActivity(), "tazhaohuan_click");
                        } else {
                            ToastUtil.show(getContext(), getResources().getString(R.string.str_calltips));
                        }
                    }
                }
                break;
            case R.id.tv_mine_supper_bt:
                RoomPushShortActivity.startActivity(getActivity());
                break;

        }

    }

    private void loaUserInfo() {
        loadUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getUserInfo(userId)).setTag(this.hashCode()).request(this);
    }

    private void loadFamilyUserInfo(long userId) {
        loadFamilyUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getFamilyInfoByUid(userId)).setTag(this.hashCode()).request(this);
    }

    private void loadMineDynamic() {
        loadMineDynamicCommand = ProtoRequestHelper.task(ProtoHttpFactory.getProfileDynamic(userId, mineDynamicMaxId, count)).setTag(this.hashCode()).request(this);
    }

    private void loadSupperdekaron(long maxId, int count) {
        loadMineSupperCommand = ProtoRequestHelper.task(ProtoHttpFactory.getProfileSupper(userId, maxId, count)).setTag(this.hashCode()).request(this);
    }

    private void loadMineLikeDynamic() {
        loadMineDynamicLikeCommand = ProtoRequestHelper.task(ProtoHttpFactory.getProfileLikeDynamic(userId, beforeTime, count)).setTag(this.hashCode()).request(this);
    }


    private void getSuggest() {
        loadRecommendUserCommand = ProtoRequestHelper.task(ProtoHttpFactory.getSuggest(3)).setTag(this.hashCode()).request(this);
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        super.onRequestSuccess(command, data);
        refreshFinish();
        if (command.equals(loadUserCommand)) {
            Result<UserInfoModel> result = JSON.parseObject(data, new TypeReference<Result<UserInfoModel>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                userInfoModel = result.data;
                if (userInfoModel != null) {
                    refreshView();
                    ImayLogUtil.log(data);
                    saveUserInfo(result.data);
                    if (isCallLiveClicked) {
                        if (userInfoModel.getUser() != null) {
                            if (userInfoModel.getUser().getLiveStatus() == 1) {
                                ToastUtil.show(getContext(), R.string.error_3000);
                            } else {
                                HoldCallLiveActivity.startActivity(getActivity(), userInfoModel.getUser().getUid(), userInfoModel.getUser().getNick());
                            }
                            isCallLiveClicked = false;
                        }
                    }
                }
            }
        } else if (command.equals(loadMineDynamicCommand)) {
            Result<List<FeedModel>> result = JSON.parseObject(data, new TypeReference<Result<List<FeedModel>>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                mineDynamicList.addAll(result.data);
                bindAdapterByTab();
            }
        } else if (command.equals(loadMineDynamicLikeCommand)) {
            Result<ProfileLikeDynamicModel> result = JSON.parseObject(data, new TypeReference<Result<ProfileLikeDynamicModel>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                if (result.data.getFeeds() == null || result.data.getFeeds().isEmpty()) {
                    return;
                }
                likeDynamicList.addAll(result.data.getFeeds());
                bindAdapterByTab();
                beforeTime = result.data.getLastLikeTime();
            }
        } else if (command.equals(createFollowCommand) || command.equals(cancelFollowCommand)) {
            Result<CreateFollowModel> result = JSON.parseObject(data, new TypeReference<Result<CreateFollowModel>>() {
            }.getType());
            if (result.result == CodeSuccess) {
                if (userInfoModel.getUser() != null) {
                    userInfoModel.getUser().setMyFollow(command.equals(createFollowCommand));
                }
                userInfoModel.getStat().setFollower(result.data.getCountFans());
                refreshView();
            }

        } else if (command.equals(loadRecommendUserCommand)) {
            Result<List<UserModel>> listResult = JSON.parseObject(data, new TypeReference<Result<List<UserModel>>>() {
            }.getType());
            if (listResult.result == CodeSuccess) {
                recommendUserModels.clear();
                recommendUserModels.addAll(listResult.data);
                bindRecommendUserAdapter();
            }
        } else if (command.equals(likeCreateRequest)) { // 点赞
            //EventHelper.postDynamicsUpdate(); // 动态信息改变
        } else if (command.equals(likeDelRequest)) { // 取消赞
            EventHelper.postDynamicsUpdate(null); // 动态信息改变
        } else if (command.equals(updateInfoCommand)) {
            ResultNoData result = JSON.parseObject(data, ResultNoData.class);
            if (result.result == CodeSuccess) {
                saveUserInfo(userInfoModel);
                if (userInfoModel.getUser() == null) {
                    return;
                }
                GlideUtil.loadCircleImage(iv_user_head_img, userInfoModel.getUser().getImgHead(), R.mipmap.pnl_00_head108);
            } else {
                ErrorResult.toastError(getActivity(), result.result);
            }
        } else if (command.equals(loadMineSupperCommand)) {
            try {
                Result<ArrayList<ShortLiveInfoModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<ShortLiveInfoModel>>>() {
                }.getType());
                if (result.result == CodeSuccess && result.data != null) {
                    int count = result.data.size();
                    if (mineSupperMaxId == 0) {
                        mdatas.clear();
                    }
                    for (int i = 0; i < count; i = i + 1) {
                        SupperModelType supperModelType = new SupperModelType();
                        ShortLiveInfoModel shortLiveInfoModel = result.data.get(i);
                        supperModelType.setShortLiveInfoModel(shortLiveInfoModel);
                        mdatas.add(supperModelType);
                    }

                    if (mdatas.size() > 0 || mineSupperMaxId == 0) {
                        supperTypeAdapter.notifyDataSetChanged();
                    }
                    bindAdapterByTab();
                }
            } catch (Exception e) {

            }
        } else if (command.equals(loadFamilyUserCommand)) {
            try {
                Result<FamilyUserInfo> result = JSON.parseObject(data, new TypeReference<Result<FamilyUserInfo>>() {
                }.getType());
                if (result.result == CodeSuccess && result.data != null) {
                    familyUserInfo = result.data;
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        super.onRequestError(command, code, message);
        //ErrorResult.toastError(getActivity(), code);
        refreshFinish();
        if (currentTab == SUPPER) {
            bindShortLiveAdapter();
        }
    }

    /**
     * 根据userid 来判断是不是主页的个人页
     */
    private boolean isHomeProfile() {
        return (0 == userId);
    }

    /**
     * 根据userid 来判断是不是自己的个人页
     */
    private boolean isSelf() {
        if (UserInfoCache.getUserInfo().getUser() == null) {
            return false;
        }
        return (UserInfoCache.getUserInfo().getUser().getUid() == userId);
    }

    private void setViewHide() {
        if (isHomeProfile()) {
            btn_follow.setVisibility(View.GONE);
            iv_recommend.setVisibility(View.GONE);
            line_other_profile.setVisibility(View.GONE);
        } else {
            Drawable drawable = getResources().getDrawable(R.mipmap.ico_05_xinfeng);

            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
            tv_marcket.setText(R.string.mine_private_message);
            tv_marcket.setCompoundDrawables(drawable, null, null, null);
            $(R.id.ll_balance, mUserInfoHeaderView).setVisibility(View.GONE);
            $(R.id.ll_profile_meili, mUserInfoHeaderView).setVisibility(View.GONE);
        }
    }

    private void bindShortLiveAdapter() {
        if (mdatas == null || mdatas.size() == 0) {
            ll_empty_view.setVisibility(View.GONE);
            fl_empty_view_profile.setVisibility(View.VISIBLE);
            if (view_supper_layout != null) {
                view_supper_layout.setVisibility(View.VISIBLE);
                View tv_mine_supper_bt = $(R.id.tv_mine_supper_bt, view_supper_layout);
                TextView tv_mine_supper_tips = $(R.id.tv_mine_supper_tips, view_supper_layout);
                if (isHomeProfile()) {
                    tv_mine_supper_bt.setVisibility(View.VISIBLE);
                    tv_mine_supper_bt.setOnClickListener(this);
                } else {
                    tv_mine_supper_bt.setVisibility(View.INVISIBLE);
                    tv_mine_supper_tips.setText(getResources().getString(R.string.str_donothingsupper));
                }
            }
        } else {
            fl_empty_view_profile.setVisibility(View.GONE);
            ll_empty_view.setVisibility(View.GONE);
        }
    }

    private void bindFollowAdapter(List<Object> itemEntities) {
        tempList.clear();
        tempList.addAll(itemEntities);
        linearManager.getmAdapter().setNewData(tempList);

        ll_empty_view.setVisibility(tempList.isEmpty() ? View.VISIBLE : View.GONE);
        fl_empty_view_profile.setVisibility(tempList.isEmpty() ? View.VISIBLE : View.GONE);
        if (view_supper_layout != null) {
            view_supper_layout.setVisibility(View.GONE);
        }
    }

    private void bindMineAdapter(List<Object> itemEntities) {
        tempList.clear();
        tempList.addAll(itemEntities);
        if (isHomeProfile()) {
            mineAdapter.setNewData(tempList);
        } else {
            linearManager.getmAdapter().setNewData(tempList);

        }
        ll_empty_view.setVisibility(tempList.isEmpty() ? View.VISIBLE : View.GONE);
        fl_empty_view_profile.setVisibility(tempList.isEmpty() ? View.VISIBLE : View.GONE);
        if (view_supper_layout != null) {
            view_supper_layout.setVisibility(View.GONE);
        }
    }


    private void swicthLayout() {
        if (currentTab == SUPPER) {
            if (linearManager.getmAdapter().getHeaderLayoutCount() > 0) {
                linearManager.getmAdapter().removeHeaderView(mUserInfoHeaderView);
            }
            if (mineAdapter.getHeaderLayoutCount() > 0) {
                mineAdapter.removeHeaderView(mUserInfoHeaderView);
            }
            if (supperTypeAdapter.getHeaderLayoutCount() == 0) {
                supperTypeAdapter.addHeaderView(mUserInfoHeaderView);
            }
            rcv_profile_dynamic.setLayoutManager(new GridLayoutManager(getActivity(), 3));
            rcv_profile_dynamic.removeItemDecoration(itemDecoration);
            rcv_profile_dynamic.setAdapter(supperTypeAdapter);
            if (itemSupperDecoration == null) {
                itemSupperDecoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                        .size((int) getResources().getDimension(R.dimen.size_2dp)).color(Color.WHITE)
                        .build();
            }
            rcv_profile_dynamic.addItemDecoration(itemSupperDecoration);
        } else if (currentTab == FOLLOW) {
            if (mineAdapter.getHeaderLayoutCount() > 0) {
                mineAdapter.removeHeaderView(mUserInfoHeaderView);
            }
            if (linearManager.getmAdapter().getHeaderLayoutCount() == 0) {
                supperTypeAdapter.removeHeaderView(mUserInfoHeaderView);
                linearManager.getmAdapter().addHeaderView(mUserInfoHeaderView);
            }
            if (itemSupperDecoration != null) {
                rcv_profile_dynamic.removeItemDecoration(itemSupperDecoration);
            }
            rcv_profile_dynamic.removeItemDecoration(itemDecoration);
            rcv_profile_dynamic.addItemDecoration(itemDecoration);
            rcv_profile_dynamic.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
            rcv_profile_dynamic.setAdapter(linearManager.getmAdapter());
        } else {
            if (supperTypeAdapter.getHeaderLayoutCount() > 0) {
                supperTypeAdapter.removeHeaderView(mUserInfoHeaderView);
            }
            if (isHomeProfile()) {
                if (linearManager.getmAdapter().getHeaderLayoutCount() > 0) {
                    linearManager.getmAdapter().removeHeaderView(mUserInfoHeaderView);
                }
                if (mineAdapter.getHeaderLayoutCount() == 0) {
                    mineAdapter.addHeaderView(mUserInfoHeaderView);
                }
                rcv_profile_dynamic.setLayoutManager(new GridLayoutManager(getActivity(), 3));
                rcv_profile_dynamic.removeItemDecoration(itemDecoration);
                rcv_profile_dynamic.setAdapter(mineAdapter);
                if (itemSupperDecoration == null) {
                    itemSupperDecoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                            .size((int) getResources().getDimension(R.dimen.size_2dp)).color(Color.WHITE)
                            .build();
                }
                rcv_profile_dynamic.addItemDecoration(itemSupperDecoration);

            } else {
                if (linearManager.getmAdapter().getHeaderLayoutCount() == 0) {
                    linearManager.getmAdapter().addHeaderView(mUserInfoHeaderView);
                }
                rcv_profile_dynamic.removeItemDecoration(itemDecoration);
                rcv_profile_dynamic.addItemDecoration(itemDecoration);
                rcv_profile_dynamic.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
                rcv_profile_dynamic.setAdapter(linearManager.getmAdapter());
            }

        }
    }


    /**
     * 弹心
     *
     * @param x
     * @param y
     * @param feedId
     * @param status true赞，false取消赞
     */
    @Override
    public void showHeart(float x, float y, int feedId, boolean status) {
        if (status) {
            hlv_profile_dynamics_like.showHeartView(x, y - ((BaseActivity) getActivity()).getTitleBar().getMeasuredHeight());
            likeCreate(feedId);// 点赞
        } else {
            likeDel(feedId);// 取消赞
        }
    }


    @Override
    public void onVoiceClick(int position) {
        linearManager.setVoice(position);

    }

    @Override
    public void jinClick(String label) {
        LabelFeedsActivity.startActivity(getActivity(), label);

    }

    @Override
    public void atClick(String nick, long uid) {
        ProfileActivity.start(getActivity(), uid);
    }

    @Override
    public void suggestTouch(boolean status) {

    }

    @Override
    public void onPause() {
        super.onPause();
        playerPosition = linearManager.stop();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (playerPosition != -1) {
            linearManager.play(playerPosition);
        }
    }

    /**
     * 如果是自己的个人页面,则缓存用户信息
     *
     * @param model
     */
    private void saveUserInfo(UserInfoModel model) {
        if (isHomeProfile()) {
            UserInfoCache.saveUserInfo(model);
            if (model.getMoney().getDiadmonRecharge() == 0) {
                loadFirstRecharge(CONFIG_SWITCH_RECHARGE_TIP, CONFIG_VALUE_RECHARGE_TIP_URL1, CONFIG_VALUE_RECHARGE_TIP_URL2);
            }
        }
    }

    private void initUserInfoChangeListener() {
        userInfoChangeListener = new IMYTBASObject(false);
        userInfoChangeListener.stringCommand = EventHelper.EVENT_UPDATE_USER_INFO;
        userInfoChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (isHomeProfile()) {
                    userInfoModel = UserInfoCache.getUserInfo();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshView();
                        }
                    });
                }
            }
        });
        userInfoChangeListener.addEventListenWithTBASObject();
    }

    private void initShortLiveChangeListener() {
        shortLiveChangeListener = new IMYTBASObject(false);
        shortLiveChangeListener.stringCommand = EventHelper.EVENT_UPDATE_PROFILE_SHORT_LVEE;
        shortLiveChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                if (isHomeProfile()) {
                    mineSupperMaxId = 0;
                    loadSupperdekaron(mineSupperMaxId, suppercount);
                }
            }
        });
        shortLiveChangeListener.addEventListenWithTBASObject();
    }

    @Override
    public void onDestroy() {
        linearManager.release();
        if (userInfoChangeListener != null) {
            userInfoChangeListener.destroy();
        }
        if (followChangeListener != null) {
            followChangeListener.destroy();
        }
        if (followChangeListener != null) {
            followChangeListener.destroy();
        }
        if (moneyInfoListener != null) {
            moneyInfoListener.destroy();
        }
        if (levelListener != null) {
            levelListener.destroy();
        }
        if (dynamicsupdate != null) {
            dynamicsupdate.destroy();
        }
        if (mDataSetManager != null) {
            mDataSetManager.unregisterDataNotify();
        }
        super.onDestroy();
    }

    private void bindRecommendUserAdapter() {
        if (profileRecommendAdapter == null) {
            profileRecommendAdapter = new ProfileRecommendAdapter(recommendUserModels);
            profileRecommendAdapter.setOnItemChildClickListener(this);
            rv_recommend.setAdapter(profileRecommendAdapter);
        } else {
            profileRecommendAdapter.setNewData(recommendUserModels);
            profileRecommendAdapter.notifyDataSetChanged();
        }

    }

    /**
     * 完成刷新
     */
    public void refreshFinish() {
        if (profile_dynamics_trl_refresh != null) {
            if (profile_dynamics_trl_refresh.isRefreshing()) {
                profile_dynamics_trl_refresh.finishRefreshing();
            } else {
                profile_dynamics_trl_refresh.finishLoadmore();
            }
        }
    }

    private void bindAdapterByTab() {
        switch (currentTab) {
            case SUPPER:
                bindShortLiveAdapter();
                break;
            case MINE:
                bindMineAdapter(mineDynamicList);
                break;
            case FOLLOW:
                bindFollowAdapter(likeDynamicList);
                break;
        }
    }

    private void loadMore() {
        switch (currentTab) {
            case SUPPER: {
                if (mdatas != null && mdatas.size() > 0) {
                    SupperModelType supperModelType = (SupperModelType) mdatas.get(mdatas.size() - 1);
                    mineSupperMaxId = supperModelType.getShortLiveInfoModel().getShortLiveId();
                    loadSupperdekaron(mineSupperMaxId, suppercount);
                } else {
                    refreshFinish();
                }
                break;
            }
            case MINE:
                int size = mineDynamicList.size();
                if (size > 0) {
                    mineDynamicMaxId = ((FeedModel) mineDynamicList.get(size - 1)).getFeedId();
                }
                loadMineDynamic();
                break;
            case FOLLOW:
                loadMineLikeDynamic();
                break;
        }

    }

    private void refreshData() {
        mineDynamicList.clear();
        likeDynamicList.clear();
        beforeTime = 0;
        mineDynamicMaxId = 0;
        mineSupperMaxId = 0;
        loaUserInfo();
        if (isHomeProfile() || isSelf()) {
            loadFamilyUserInfo(AccountManager.getInstance().getUid());
            if(isHomeProfile()){
                FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
            }
        } else {
            loadFamilyUserInfo(userId);
        }
        loadMineDynamic();
        loadSupperdekaron(mineSupperMaxId, suppercount);
        loadMineLikeDynamic();
        if (profileRecommendAdapter != null) {
            getSuggest();
        }
    }

    /**
     * 点赞
     */
    protected void likeCreate(int feedId) {
        likeCreateRequest = ProtoRequestHelper.task(ProtoHttpFactory.likeCreate(feedId)).setTag(this.hashCode()).request(this);
    }

    protected void likeDel(int feedId) {
        likeDelRequest = ProtoRequestHelper.task(ProtoHttpFactory.likeDel(feedId)).setTag(this.hashCode()).request(this);
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.btn_recommend_follow:
                followControl.followChanged(getActivity().getApplicationContext(), recommendUserModels.get(position), false);
                break;
            case R.id.iv_recommend_head_img:
            case R.id.tv_recommend_user_name:
                ProfileActivity.start(getActivity(), recommendUserModels.get(position).getUid());
                break;
        }
        onDynamicClick(adapter, position);

    }


    protected void registerSocketNotify() {
        followChangeListener = new IMYTBASObject(false);
        followChangeListener.stringCommand = EventHelper.EVENT_FOLLOW_UICHANGE;
        followChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                refreshFollowStatus(object.stringData);
            }
        });
        followChangeListener.addEventListenWithTBASObject();
    }

    private void refreshFollowStatus(String uidStr) {
        boolean isFollow = true;
        int sp = uidStr.indexOf("#");
        if (sp > 0) {
            uidStr = uidStr.substring(0, sp);
            isFollow = false;
        }
        int uid = Integer.parseInt(uidStr);
        if (userInfoModel.getUser() != null && userInfoModel.getUser().getUid() == uid) {
            userInfoModel.getUser().setMyFollow(isFollow);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshView();
                }
            });
        }
        if (recommendUserModels != null) {
            for (int i = 0; i < recommendUserModels.size(); i++) {
                if (recommendUserModels.get(i).getUid() == uid) {
                    recommendUserModels.get(i).setMyFollow(isFollow);
                }
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bindRecommendUserAdapter();

                }
            });
        }
        if (isHomeProfile()) {
            final int followCount = userInfoModel.getStat().getFollow();
            userInfoModel.getStat().setFollow(isFollow ? followCount + 1 : followCount - 1);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_follow_count.setText(userInfoModel.getStat().getFollow() + "");
                }
            });

        }


    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        onDynamicClick(adapter, position);

    }

    private void onDynamicClick(BaseQuickAdapter adapter, final int position) {
        if (adapter.getData() == null || adapter.getData().size() <= position) {
            return;
        }
        Object obj = adapter.getData().get(position);
        if (obj instanceof FeedModel) {
            FeedModel bean = (FeedModel) obj;
            if (isHomeProfile()) {
                DynamicActivity.start(getActivity(), bean.getFeedId(), getString(R.string.str_imay_photo), position);
            } else {
                currentTab = MINE;
                rb_mine_tab_mine.setChecked(true);
                swicthLayout();
                bindFollowAdapter(mineDynamicList);
                rcv_profile_dynamic.scrollToPosition(position + linearManager.getmAdapter().getHeaderLayoutCount());
                ThreadManager.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        linearManager.play(position + linearManager.getmAdapter().getHeaderLayoutCount());
                    }
                }, 500);
            }
        } else if (obj instanceof RoomInfoModel) {
            RoomInfoModel bean = (RoomInfoModel) obj;
            if (bean.getUser() != null) {
                RoomLiveNormalActivity.startActivity(getActivity(), bean);
            }
        } else if (obj instanceof SupperModelType) {
            List<Long> infoModels = new ArrayList<>();
            for (int i = 0; i <= position; i++) {
                SupperModelType supperModelType = (SupperModelType) adapter.getData().get(i);
                infoModels.add(supperModelType.getShortLiveInfoModel().getShortLiveId());
            }
            if (userInfoModel.getUser() != null) {
                RoomLiveShortActivity.startActivity(getActivity(), infoModels, userInfoModel.getUser().getUid());
            }
        }
    }


    private void addMoneyInfoReceiveListener() {
        moneyInfoListener = new IMYTBASObject(false);
        moneyInfoListener.stringCommand = EventHelper.EVENT_PROFILE_MONEY;
        moneyInfoListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                ProfileSocketMoneyModel profileSocketMoneyModel = JSON.parseObject(imytbasObject.stringData, new TypeReference<ProfileSocketMoneyModel>() {
                }.getType());
                if (UserInfoCache.getUserInfo().getUser() != null) {
                    if (UserInfoCache.getUserInfo().getUser().getUid() == profileSocketMoneyModel.getUid()) {
                        userInfoModel.getMoney().setDiamond(profileSocketMoneyModel.getDiamond());
                        userInfoModel.getMoney().setMeili(profileSocketMoneyModel.getMeili());
                        userInfoModel.getMoney().setMeiliGain(profileSocketMoneyModel.getMeiliGain());
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    refreshMoneyView();
                                }
                            });
                        }
                    }
                }
            }
        });
        moneyInfoListener.addEventListenWithTBASObject();
    }

    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
            case SYS_IMAGE_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri uri = data.getData();
                        String path = Dialoger.getPath(getActivity(), uri);
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(getActivity(), R.string.str_img_error);
                            return;
                        }
                        File file = ICUtils.getOutputMediaFile(getActivity());
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(getActivity());
                    } else {
                        ToastUtil.show(getActivity(), R.string.str_img_error);
                    }
                }
                break;
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                if (RESULT_OK == resultCode) {
                    if (data != null) {
                        File file = ICUtils.getOutputMediaFile(getActivity());
                        String path = data.getStringExtra("path");
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(getActivity(), R.string.str_img_error);
                            return;
                        }
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(getActivity());
                    } else {
                        ToastUtil.show(getActivity(), R.string.str_img_error);
                    }
                }
                break;
            case UCrop.REQUEST_CROP:
                if (RESULT_OK == resultCode) {
                    final Uri resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        upload(Dialoger.getPath(getActivity(), resultUri));
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    private void addLevelReceiveListener() {
        levelListener = new IMYTBASObject(false);
        levelListener.stringCommand = EventHelper.EVENT_PROFILE_LEVEL;
        levelListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                final UserUpdataLvNotify userUpdataLvNotify = JSON.parseObject(imytbasObject.stringData, UserUpdataLvNotify.class);
                if (userUpdataLvNotify == null) {
                    return;
                }
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (userUpdataLvNotify.LvType == 1) {
                                if (userInfoModel.getUser() != null) {
                                    userInfoModel.getUser().setUserLevel(userUpdataLvNotify.Lv);
                                    tv_user_level.setText(userInfoModel.getUser().getUserLevel() + "");
                                    tv_user_level.setBackgroundResource(LevelHelper.getUserLevelResId(userInfoModel.getUser().getUserLevel()));
                                }
                            } else {
                                if (userInfoModel.getUser() != null) {
                                    userInfoModel.getUser().setLiveLevel(userUpdataLvNotify.Lv);
                                    tv_anchor_level.setBackgroundResource(LevelHelper.getLiveLevelResId(userInfoModel.getUser().getLiveLevel()));
                                    tv_anchor_level.setText(userInfoModel.getUser().getLiveLevel() + "");
                                }
                            }
                        }
                    });

                }


            }
        });
        levelListener.addEventListenWithTBASObject();
    }

    // 上传头像
    public void upload(String imagePath) {
        UploadFileManager.getInstance().uploadHead(imagePath, new UploadFileManager.UploadCallBack() {
            @Override
            public void uploadSuccess(String fileUrl) {
                if (userInfoModel.getUser() != null) {
                    userInfoModel.getUser().setImgHead(fileUrl);
                    updateInfoCommand = ProtoRequestHelper.task(ProtoHttpFactory.updateUserInfo(userInfoModel)).setTag(this.hashCode()).request(ProfileFragment.this);
//                ToastUtil.show(getActivity(), "上传成功");
                }
            }

            @Override
            public void uploadFailer(int errorCode, String errorMessage) {
                ToastUtil.show(getActivity(), "上传失败");
            }
        });
    }

    private int position = -1;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        // TODO Auto-generated method stub
        super.setUserVisibleHint(isVisibleToUser);
        // 友盟统计页面跳转，重写此方法，可以保证ViewPager切换Fragment时能够准确的记录Fragment之间的跳转
        // 不用再调用Fragment的生命周期方法
        if (isCreated) {
            if (isVisibleToUser) {
                MobclickAgent.onPageStart(getClass().getSimpleName());
            } else {
                MobclickAgent.onPageEnd(getClass().getSimpleName());
            }
        }
        if (linearManager == null) {
            return;
        }
        if (isVisibleToUser) {
            if (position != -1) {
                linearManager.play(position);
            }
        } else {
            position = linearManager.stop();
        }
    }

    boolean isCreated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }

    private void getRoomInfo(long roomId) {
        ProtoRequestHelper.task(ProtoHttpFactory.getRoomInfo(roomId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<RoomInfoModel> result = JSON.parseObject(data, new TypeReference<Result<RoomInfoModel>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
//                        if (result.data.getLatitude())
                        if (result.data.getUser() != null) {
                            RoomLiveNormalActivity.startActivity(getActivity(), result.data);
                        }
                    }

                } catch (Exception e) {
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
            }
        });
    }


    @Override
    public void loadData() {
        if (isCreate) {
            if (AccountManager.getInstance().isLogined()) {
                if (isInstance) {
                    isInstance = false;
                    loaUserInfo();
                    if (isHomeProfile() || isSelf()) {
                        loadFamilyUserInfo(AccountManager.getInstance().getUid());
                        if(isHomeProfile()){
                            FamilyAccountManager.getInstance().loadFamilyUserInfo(false);
                        }
                    } else {
                        loadFamilyUserInfo(userId);
                    }
                    loadMineDynamic();
                    loadSupperdekaron(mineSupperMaxId, suppercount);
                    loadMineLikeDynamic();
                }
            }
        }
    }

    @Override
    public void clearData() {
        UserInfoCache.clearUserInfo();
        if (mineDynamicList != null) {
            mineDynamicList.clear();
        }
        if (likeDynamicList != null) {
            likeDynamicList.clear();
        }
        isInstance = true;
        bindAdapterByTab();
        clearUserView();
    }

    /**
     * 清楚控件信息
     */
    private void clearUserView() {
        tv_user_name.setText("");
        tv_imay_number.setText("");
        tv_sign.setText("");
        tv_fans_count.setText("");
        tv_follow_count.setText("");
        tv_balance.setText("");
        tv_meili.setText("");
        tv_anchor_level.setText("");
        tv_user_level.setText("");
        iv_user_head_img.setImageResource(R.mipmap.pnl_00_head108);
        Drawable drawable;
        if (userInfoModel.getUser() != null && 1 == userInfoModel.getUser().getSex()) {
            drawable = getResources().getDrawable(R.mipmap.ico_00boy);
        } else {
            drawable = getResources().getDrawable(R.mipmap.ico_00girl);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_user_name.setCompoundDrawables(drawable, null, null, null);
        btn_follow.setText("");
        tv_website.setText("");
        tv_profile_user_family_nick.setText("");
        tv_profile_user_family_nick.setVisibility(View.GONE);
    }

    private void refreshLiveStatu() {
        if (userInfoModel == null) return;
        if (userInfoModel.getUser() != null && userInfoModel.getUser().getLiveStatus() == 1) {
            tv_live_profile.setText(R.string.liveing_profile);
            iv_live_statu_profile.setImageResource(R.mipmap.ico_05_live);
        } else {
            tv_live_profile.setText(R.string.call_live_profile);
            iv_live_statu_profile.setImageResource(R.mipmap.ico_05_zhaohuanlive);
        }
    }

    public void setCallLiveRedVisible(boolean visible) {
        if (tv_unread_call_live_profile != null) {
            tv_unread_call_live_profile.setVisibility(visible ? View.VISIBLE : View.GONE);

        }
    }

    // 首充
    private void loadFirstRecharge(String... key) {
        ProtoRequestHelper.task(ProtoHttpFactory.getSysparams(key)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<List<SysparamModel>> result = JSON.parseObject(data, new TypeReference<Result<List<SysparamModel>>>() {
                }.getType());
                ImayLogUtil.log("FirstRecharge", data);
                boolean ConfigSwitchRechargeTip = false;
                String ConfigValueRechargeTipUrl1 = "";
                String ConfigValueRechargeTipUrl2 = "";
                if (result.result == CodeSuccess) {
                    for (SysparamModel sysparamModel : result.data) {
                        if (CONFIG_SWITCH_RECHARGE_TIP.equals(sysparamModel.getParamKey())) {
                            ConfigSwitchRechargeTip = sysparamModel.getValue() == 1;
                        } else if (CONFIG_VALUE_RECHARGE_TIP_URL1.equals(sysparamModel.getParamKey())) {
                            ConfigValueRechargeTipUrl1 = sysparamModel.getStringValue();
                        } else if (CONFIG_VALUE_RECHARGE_TIP_URL2.equals(sysparamModel.getParamKey())) {
                            ConfigValueRechargeTipUrl2 = sysparamModel.getStringValue();
                        }
                    }
                    if (ConfigSwitchRechargeTip && getActivity() instanceof MainActivity2 && !StringUtil.isEmpty(ConfigValueRechargeTipUrl1) && !StringUtil.isEmpty(ConfigValueRechargeTipUrl2)) {
                        ((MainActivity2) getActivity()).showFirstRechargeButton(ConfigValueRechargeTipUrl1, ConfigValueRechargeTipUrl2);
                    }
                }


            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });


    }


}
